<template>
  <section class="img-manage">
    <!-- <div class="img-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="searchQuery.pictureName"
          placeholder="请输入图片名称搜索"
          class="search-input"
          @keyup.enter.native="getList"
        />
        <div class="img-search-btn">
          <el-button class="filter-item" type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </div>
      </div> -->
    <el-collapse-transition>
      <div v-show="searchshow" class="img-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input v-model.trim="searchQuery.pictureName" placeholder="请输入图片名称搜索" class="search-input"
          @keyup.enter.native="getList" />
        <div class="img-search-btn">
          <el-button class="filter-item" type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <span class="img-search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="!searchshow" class="img-search separate">
        <div class="img-search-inner">
          <el-row type="flex">
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">图片名称</div>
                <el-input v-model.trim="listQuery.pictureName" placeholder="请输入图片名称搜索" class="search-input"
                  @keyup.enter.native="getList" />
              </div>
            </el-col>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">图片分类</div>
                <el-cascader v-model.trim="listQuery.classifyId" style="width:100%" clearable :props="createClassifyProps"
              :options="classifyOptions" />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="img-search-btn">
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="handleReset">重置</el-button>
          <span class="img-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>图片管理</span>
      </section>

      <el-button style="margin-left: 10px" @click="handleSetting">批量设置</el-button>
      <el-button style="margin-left: 10px" @click="handleCreate('', 'created')">上传图片
      </el-button>
      <!-- <el-button style="margin-left: 10px" @click="handleSelectPlatform">选取SaaS平台图片
      </el-button> -->
      <section class="main-buttons-btns" />
    </section>
    <section class="url-table">
      <v-table ref="tabs" :list-loading="loading" :selection="true" :filter-column="filtercolumn" tag="imgLibrary"
        :source-arr="['imgURL']" :list="dataList" style="width: 100%" @handleSelectionChange="handleSelectionChange">
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isForce != 'SF01'" type="text" size="small"
              @click="handleCreate(scope.row, 'update')">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleShow(scope.row)">
              链接
            </el-button>

            <!-- v-if="scope.row.typeCode!=='KCLX04'" -->
            <el-button type="text" size="small" @click="handleView(scope.row)">
              预览
            </el-button>
            <el-button v-if="scope.row.isForce != 'SF01'" type="text" size="small" @click="changeStatus(scope.row)">
              {{ scope.row.status === 'ZT01' ? '禁用' : '启用' }}
            </el-button>
            <el-button v-if="scope.row.isForce != 'SF01'" type="text" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button
                v-if="scope.row.transcodeStatus !== '2' && scope.row.isForce !== 'SF01'"
                size="small"
                type="text"                
                @click="handleDonwload(scope.row)"
              >
                下载</el-button>
          </template>
        </el-table-column>
      </v-table>
      <div class="btn-pagion fix">
        <pagination v-show="total > 0" :total="total" :page.sync="pageQuery.page" :limit.sync="pageQuery.pageSize"
          @pagination="getList" />
      </div>
    </section>
    <el-dialog title="链接地址" :visible.sync="dialogVisible1" width="55%">
      <div class="btns">
        <el-button type="primary" @click="copyUrl('oss')">复制OSS地址</el-button>
        <el-button type="primary" @click="copyUrl('doc')">复制本地地址</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog v-el-drag-dialog :title="viewType === 'created' ? '新增图片' : '编辑图片'" :visible.sync="classType" center
      :close-on-click-modal="false" destroy-on-close @closed="clearForm">
      <section class="main-table">
        <el-form ref="form" :model="fileInfo" :rules="rules" label-width="120px" class="form">
          <el-form-item label="上传图片" prop="imgId">
            <div v-if="!fileInfo.imgId" class="selectbtn" @click="uploadFile.showUpload = true">开始上传</div>
            <template v-else>
              <div class="select-data">
                <el-image :src="view + fileInfo.imgId" :preview-src-list="[view + fileInfo.imgId]">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                  <div slot="placeholder" class="image-slot">
                    <i class="el-icon-loading" />
                  </div>
                </el-image>
                <!--                {{ fileInfo.pictureName }}
                  <i class="el-icon-close" @click="clearFile" />-->
              </div>
            </template>
            <Upload v-if="uploadFile.showUpload" ref="upload" :accept="uploadFile.accept" :limit="1" :show-chunks="true"
              :multiple="false" :chunk-size="uploadFile.chunksize" @close="uploadFile.showUpload = false"
              @success="uploadSuccess">
              <div slot="tip" class="upload-tip">
                <i class="el-icon-info" />
                : 只能上传：图片文件
              </div>
            </Upload>
          </el-form-item>
          <el-form-item label="图片名称">
            <el-input v-model.trim="fileInfo.pictureName" maxlength="100" placeholder="请输入图片名称" />
          </el-form-item>
          <el-form-item label="选择分类" prop="classifyId">
            <el-cascader ref="classify" v-model="classifyId" style="width:100%" clearable :props="createClassifyProps"
              :options="classifyOptions" />
          </el-form-item>

        </el-form>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="classType = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="handleImgType()">确定</el-button>
      </div>
    </el-dialog>
    <FilePreview v-if="dialogVisible" type="image" :file-path="getUrl(fileInfo, 'oss')" @close="dialogVisible = false" />
    <!--批量设置-->

    <el-dialog v-el-drag-dialog title="批量设置" :visible.sync="batchSettingDialog" center :close-on-click-modal="false"
      destroy-on-close @closed="clearSettingForm">
      <section class="main-table">
        <el-form ref="form" :rules="rules" label-width="120px" class="form">
          <el-form-item label="批量命名">
            <el-input v-model.trim="name" maxlength="100" placeholder="请输入图片名称" />
          </el-form-item>
          <el-form-item label="起始编号">
            <el-input v-model.trim="startNumber" maxlength="100" placeholder="请输入编号" />
          </el-form-item>
          <el-form-item label="转移至分类下" prop="classifyId">
            <el-cascader ref="classify" v-model="classifyId" style="width:100%" clearable :props="createClassifyProps"
              :options="classifyOptions" />
          </el-form-item>

        </el-form>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="clearSettingForm">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="handleBatchSetting()">确定</el-button>
      </div>
    </el-dialog>
</section>
</template>

<script>
import VTable from '@/components/Table'
import Upload from '../components/upload'
import Pagination from '@/components/Pagination'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { queryFileList, deleteFile, addFile, getDictByCode, setStatus, getClassifyTree, batchSetting } from '../api'
import { parseTime } from '@/utils'
import { fomatterTime } from '@/filters'
import FilePreview from '@/components/FilePreview'

function conver(limit) {
  limit = Number(limit)
  var size = ''
  if (limit < 0.1 * 1024) {
    // 如果小于0.1KB转化成B
    size = limit.toFixed(2) + 'B'
  } else if (limit < 0.1 * 1024 * 1024) {
    // 如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + 'KB'
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {
    // 如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
  } else {
    // 其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }

  var sizestr = size + ''
  var len = sizestr.indexOf('\.')
  var dec = sizestr.substr(len + 1, 2)
  if (dec === '00') {
    // 当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
  }
  return sizestr
}

export default {
  name: 'ImgLibrary',
  components: {
    VTable,
    Pagination,
    FilePreview,
    Upload
  },
  directives: { elDragDialog },
  data() {
    return {
      searchshow: true,
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      },
      classifyOptions: [],
      classifyId: '',
      classType: false,
      rules: {},
      loading: false,
      dataList: [],
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      isShowFileDialog: false,
      dialogVisible: false,
      fileInfo: {
        pictureName: ''
      },
      view: '/API-DOCUMENT/document/file/download?id=',
      total: 0,
      pageQuery: {
        page: 1,
        pageSize: 10
      },
      dialogVisible1: false,
      form: {
        type: '',
        title: '',
        scene: '',
        sort: ''
      },
      searchQuery: { pictureName: '' },
      listQuery: { pictureName: '',classifyId:'' },
      dict: {
        WJLX: []
      },
      selectFrom: {},
      uploadFile: {
        showUpload: false,
        accept: 'image/*',
        chunksize: 10 * 1024 * 1024,
        file: '',
        oldfile: '',
        fileType: 'img'
      },
      imgClassId: '',
      viewType: 'created',
      // 批量设置
      batchSettingDialog: false,
      name: '',
      startNumber: '',
      pictureName: '',
      startNum: '',
      multipleSelection: [],
    }
  },
  created() {
    this.getTreeData()
    this.getList()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  mounted() {
  },
  methods: {
    handleDonwload(item) {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-DOCUMENT/document/file/download?id=' + item.imgId
      console.log(link.href,1111111)
      link.setAttribute('download', item.pictureName)
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    getTreeData() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'FLLX_TP' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    handleImgType() {
      if (!this.classifyId || !this.fileInfo.imgId) {
        this.$message({
          type: 'error',
          message: !this.classifyId ? '请选择分类' : '请上传照片'
        })
        return
      } else {
        this.fileInfo.classifyId = this.classifyId ? this.classifyId : ''
        this.handleSubmit(this.fileInfo)
      }
    },
    selectType(data) {
      this.imgClassId = data.id
    },
    // handleSelectPlatform() {
    //   this.$router.push({
    //     path: '/contentRepository/imgLibrary/SelectCourse4platform',
    //     query: {}
    //   })
    // },
    uploadSuccess(id, files, data) {
      if (id) {
        this.$set(this.fileInfo, 'pictureName', files[0].name)
        // this.fileInfo.pictureName = files[0].name
        this.fileInfo.imgId = id
        this.fileInfo.spaceUsage = files[0].size
        this.fileInfo.pictureSize = data.proportion
        this.uploadFile.file = files[0]
        this.uploadFile.showUpload = false
      }
    },
    clearFile() {
      this.uploadFile.file = ''
    },
    handleSubmit(fileInfo) {
      // const request = JSON.stringify(fileInfo)
      fileInfo['flag'] = 'y'
      addFile(fileInfo, this.viewType).then((res) => {
        if (res.data.code === '200') {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.classType = false
          this.getList()
        }
      })
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((response) => {
            this.dict[code] = response.data.data[0].list
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      this.pageQuery.page = 1
      this.getList()
    },
    handleShow(row) {
      this.selectFrom = row
      this.dialogVisible1 = true
    },
    /**
     * 复制地址
     */
    copyUrl(type) {
      const ths = this
      this.$copyText(this.getUrl(ths.selectFrom, type)).then(
        function (e) {
          ths.$message.success('复制成功')
        },
        function (e) {
          ths.$message.error('复制失败，请手动复制')
        }
      )
    },
    /**
     * 获取图片地址
     */
    getUrl(row, tpye) {
      // return this.view + row.imgId
      if (tpye === 'oss') {
        return row.imgURL
      } else {
        return this.view + row.imgId
      }
    },
    formattingUrl(row) {
      if (this.isOss) {
        return row.ossPath
      } else {
        return this.view + row.id
      }
    },
    /**
    *多选
    */
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },

    handleCreate(row = '', type) {
      this.viewType = type
      if (type === 'update') {
        this.fileInfo = Object.assign({}, row)
        console.log(row, 'row')
        this.classifyId = row.classifyId
        console.log(this.classifyId, 'id')
      }
      this.classType = true
      this.getTreeData()
    },
    handleClose() {
      this.isShowFileDialog = false
    },

    handleDelete(row) {
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          deleteFile({ id: row.id })
            .then((res) => {
              loading.close()
              this.$message({
                type: 'success',
                message: res.data.msg || '操作成功'
              })
              this.getList()
            })
            .catch((err) => {
              loading.close(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getList() {
      this.loading = true
      const params = {
        ...this.searchQuery,
        ...this.pageQuery
      }
      if (this.searchshow) {
        params['pictureName'] = this.searchQuery.pictureName
      } else {
        params['pictureName'] = this.listQuery.pictureName
        params['classifyId'] = this.listQuery.classifyId.length > 0 ? this.listQuery.classifyId : ''
      }
      queryFileList(params)
        .then((res) => {
          this.loading = false
          if (res.data.code === '200') {
            this.dataList = res.data.data.rows
            this.total = res.data.data.total || 0
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleView(row) {
      this.fileInfo = Object.assign({}, row)
      this.dialogVisible = true
    },
    filtercolumn(scope, item) {
      if (item === 'spaceUsage') {
        return `${conver(scope.row.spaceUsage)} `
      } else if (item === 'uploadTime') {
        return scope.row.uploadTime
      } else if (item === 'imgId') {
        return this.view + scope.row.imgId
      } else if (item === 'duration') {
        return scope.row[item] ? fomatterTime(scope.row[item]) : ''
      } else {
        return scope.row[item]
      }
    },
    changeStatus(row) {
      setStatus({ id: row.id, status: row.status === 'ZT01' ? 'ZT02' : 'ZT01' }).then((res) => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.getList()
      })
    },
    handleReset() {
      this.pageQuery.page = 1
      this.listQuery.classifyId = ''
      this.searchQuery.pictureName = ''
      this.searchQuery.classifyId = ''
      this.getList()
    },
    // 上传图片对话框关闭时的回调，清楚内容
    clearForm() {
      this.classifyId = ''
      this.fileInfo = {}
      this.uploadFile.file = ''
    },
    /**
     * 批量设置图片名称和图片分类
     */
    async handleSetting() {
      this.batchSettingDialog = true
      await this.getTreeData()
    },
    // 清除批量设置内容
    clearSettingForm() {
      this.classifyId = ''
      this.name = ''
      this.startNumber = ''
      this.batchSettingDialog = false
    },
    /**
     * 批量设置名称、分类
     */
    handleBatchSetting() {
      return new Promise((resolve, reject) => {
        if (this.multipleSelection.length > 0) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = {
            id: this.multipleSelection.map(item => {
              return item.id
            }).join(','),
            pictureName: this.name,
            startNum: this.startNumber,
            classifyId: this.classifyId
          }
          batchSetting(params)
            .then((res) => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.clearSettingForm()
              this.getList()
              this.$refs.tabs.handleChangeSelection(this.multipleSelection)
            }).catch((error) => {
              reject(error)
              loading.close()
            })
        } else {
          this.$message({
            type: 'warning',
            message: '请选择需要修改的图片'
          })
        }
      })

    }
  }
}
</script>

<style lang="scss">
$dark_gray: #bfced6;

.img-manage {
  padding: 10px;

  .select-data {
    display: inline-block;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    width: 150px;
    height: 100px;

    i {
      cursor: pointer;
      padding-left: 5px;
    }

    .el-image {
      width: 100%;
      height: 100%;

      >img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .selectbtn {
    display: inline-block;
    width: 120px;
    background: rgba(255, 255, 255, 1);
    @include border-color(1px, dotted, $mainColor);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    @include font-color($mainColor);
    text-align: center;
    cursor: pointer;
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);

      .tip {
        color: red;
        font-size: 18px;
        margin-left: 15px;
      }
    }
  }

  .url-table {
    margin-top: 10px;

    .classify-tab {
      width: 100%;
      margin: 10px 0;
      padding: 0 10px;
      background-color: #fff;
      display: flex;
      border-radius: 4px;

      .el-tabs__nav-wrap::after {
        display: none;
      }

      .el-tabs__header {
        margin: 0;
      }
    }
  }

  .content {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    padding: 35px;
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    align-content: center;
  }

  .img-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .img-search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .img-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .img-search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .img-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .btns {
    display: flex;
    justify-content: center;
    padding: 10px;
  }
}
</style>
